# -*- coding: utf-8 -*-
import urllib2
from lxml import etree

HDIN_FRONTPAGE = "http://my.hdin.tv"

class Hdin(object):
    def __init__(self, user=None, password=None):
        """ Авторизуемся на сайте и парсим сериалы """
        self.logIn(user, password)

    def logIn(self, user=None, password=None):
        """ Авторизуемся на сайте через urllib2 и HTTPBasicAuthHandler() """

        if user is None:
            raise Exception("Username is required")

        if password is None:
            raise Exception("Password is required")

        self.user = user.strip()
        self.password = password.strip()

        # Создаем хендлер для авторизации по http
        auth_handler = urllib2.HTTPBasicAuthHandler()
        auth_handler.add_password(realm='HDinTV Access',
                                  uri=HDIN_FRONTPAGE,
                                  user=self.user,
                                  passwd=self.password)
        opener = urllib2.build_opener(auth_handler)

        # А теперь можно и зайти
        urllib2.install_opener(opener)
        self.page = urllib2.urlopen(HDIN_FRONTPAGE).read()
        #self.dumpPage()

    #def dumpPage(self):
    #    """ Исключительно в тестовых целях """
    #    print self.page

    def getPath(self):
        """ Возвращает полный адрес сайта вместе с юзером и паролем """
        return "http://%s:%s@my.hdin.tv" % (self.user, self.password)

    def getSerials(self):
        """ Парсим главную страницу и вытягиваем все сериалы с нее """
        tree = etree.fromstring(self.page, etree.HTMLParser())

        self.serials = []
        shows = tree.xpath("//div[@class='ssplash' or @class='ssplash0']")
        for show in shows:
            atitle = show.xpath("./div/a[@class='title']")[0]
            showName = unicode(atitle.xpath("./text()")[0])
            showLink = HDIN_FRONTPAGE + '/' + unicode(atitle.xpath("./@href")[0])
            showNameLink = showLink.split("/")[3]
            showImage = self.getPath() + '/images/' + str(show.xpath("./@style")[0]).split('/images/')[1].split("')")[0]
            self.serials.append({ "name": showName, "namelink": showNameLink, "link": showLink, "image": showImage })

        return self.serials

    def getSerialSeasons(self, serial=None):
        """ Возвращает лист со списком эпизодов в сериале с названием serial.
            Номера эпизодов в юникоде (чтобы потом удобно в url подставлять),
            так что потом требуется сделать int() """
        if serial is None:
            raise Exception("Serial url is required")

        serialLink = "%s/%s/index.html" % (HDIN_FRONTPAGE, serial)
        self.showPage = urllib2.urlopen(serialLink).read()
        tree = etree.fromstring(self.showPage, etree.HTMLParser())
        seasons = tree.xpath("//h2/span")
        result = []
        for season in seasons:
            result.append("%02.0i" % int(season.xpath('./text()')[0]))

        return result

    def getSeasonEpisodes(self, serial=None, season=None):
        """ Возвращает лист со всеми эпизодами для данного сезона сериала
            по ссылке link. Ничего необычного. Стырил у бобука кусочек :-[ """
        if serial is None:
            raise Exception("Serial url is required")
        if season is None:
            raise Exception("Season is required")

        serialLink = "%s/%s/index.html" % (HDIN_FRONTPAGE, serial)
        self.showPage = urllib2.urlopen(serialLink).read()
        tree = etree.fromstring(self.showPage, etree.HTMLParser())
        seasons = tree.xpath("//div[@class='season']")
        season = int(season)
        episodes = seasons[season-1].xpath("./div/span[@class='episode']")

        result = []
        for episode in episodes:
            episodeTitle = unicode(episode.xpath("./text()")[0]) + ' ' + unicode(episode.xpath('./a/text()')[0])
            [showName, seasonN, episodeN] = unicode(episode.xpath("./a/@href")[0]).split('.')[0][1:].replace('/', '-').split('-')
            image = self.getPath() + "/content/%s/%s-%s.jpg" % (showName, seasonN, episodeN)
            result.append({ "title": episodeTitle, "name": showName, "season": seasonN, "episode": episodeN, "image": image })

        return result

    def getEpisode(self, serial=None, season=None, episode=None):
        """ Возвращает словарь с параметрами эпизода. В нем прямой линк на
            эпизод, название и всякие описания """
        if serial is None:
            raise Exception("Serial url is required")
        if season is None:
            raise Exception("Season is required")
        if episode is None:
            raise Exception("Episode is required")

        episodePageUrl = "%s/%s/%s-%s.html" % (HDIN_FRONTPAGE, serial.strip(), season.strip(), episode.strip())
        self.episodePage = urllib2.urlopen(episodePageUrl).read()
        tree = etree.fromstring(self.episodePage, etree.HTMLParser())
        episodeVideo = self.getPath() + str(tree.xpath("//div[@id='iepisode']/@f")[0])
        episodeImage = self.getPath() + str(tree.xpath("//div[@id='iepisode']/@i")[0])
        episodeName  = unicode(tree.xpath("//div[@class='ehead']/div[@class='title']/text()")[0])
        serialName   = unicode(tree.xpath("//div[@class='ehead']/h1/text()")[0])

        return { "name": episodeName, "image": episodeImage, "video": episodeVideo, "serial": serialName }

